package thread;

//自己实现一个定时器

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;//执行任务

    private long time;//执行任务的时间

    public MyTimerTask(Runnable task,long time){
        this.task = task;
        this.time = time;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
    public long getTime(){
        return this.time;
    }
    public void run(){
        task.run();
    }
}

class MyTimer{

    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public void schedule(Runnable task,long delay){
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(task, delay + System.currentTimeMillis());
            queue.offer(myTimerTask);
            //唤醒
            locker.notify();
        }
    }

    public void delete(){
        synchronized(locker){
            queue.poll();
            locker.notify();
        }
    }

    public MyTimer() {
        Thread t1 = new Thread(()->{
            try {
                while (true) {
                    synchronized (locker){
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask timerTask = queue.peek();

                        if (System.currentTimeMillis() < timerTask.getTime()) {
                            locker.wait(timerTask.getTime() - System.currentTimeMillis());
                        } else {
                            timerTask.run();
                            queue.poll();
                        }
                    }
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();
    }
}
public class Demo28 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        System.out.println("main");

    }
}
